package com.hqj.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hqj.entity.TMenu;

import java.util.*;

public class MenuUtil {

    public static List<Map<String,Object>> createMenuJson(List<TMenu> list){
        List<Map<String,Object>> menus = new ArrayList<>();
        List menuList = new ArrayList<>();
        //需要转换菜单的格式，方便添加属性
        for(TMenu menu:list){
            Map<String,Object> m = new LinkedHashMap<>();
            m.put("name",menu.getMenuName());
            m.put("title",menu.getMenuName());
            m.put("id",menu.getId());
            m.put("parentId",menu.getParentId());
            m.put("menuUrl",menu.getMenuUrl());
            m.put("authority",menu.getAuthority());
            m.put("spread",true);
            menus.add(m);
        }

        for(Map<String,Object> map:menus){
            if("0".equals(map.get("parentId").toString())){
                map.put("children",createBranch(map,menus));
                menuList.add(map);
            }
        }

        return menuList;
    }

    public static List createBranch(Map<String,Object> parentMap,List<Map<String,Object>> list){
        List<Map<String,Object>> childList = new ArrayList<>();
        parentMap.put("children",childList);
        for(Map childMap:list){
            if(childMap.get("parentId").toString().equals(parentMap.get("id").toString())){//true说明存在子节点
                childList.add(childMap);//添加子节点到集合
                createBranch(childMap,list);//子菜单的递归
            }
        }
        return childList;
    }


}
